package higherfunction;

import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;

/**
 * @Description: 高阶函数-简单数据流-两个元素，按照某个规则合并为一个
 * @Author: tfq
 * @Date: 2025-02-17 10:14
 */
public class SimpleStream2<T> {

    public static void main(String[] args) {
        List<Integer> list = List.of(1, 2, 3, 4, 5);

        Integer r= SimpleStream2.of(list).reduce(0, Integer::sum);
        System.out.println(r);
        Integer max= SimpleStream2.of(list).reduce(Integer.MIN_VALUE, Integer::max);
        System.out.println(max);
        Integer min= SimpleStream2.of(list).reduce(Integer.MAX_VALUE, Integer::min);
        System.out.println(min);
//        Optional<Integer> max1 = list.stream().max(Integer::compareTo);
        Optional<Integer> max1 = list.stream().max((x,y)->x<y?x:y);
        System.out.println("max:"+max1.get());
    }

    /**
     * 聚合求和、找最小/大操作规则
     *
     * @param o        初始值
     * @param operator 操作的规则
     * @return 求和、找最小/大后的结果
     */
    public T reduce(T o, BinaryOperator<T> operator) {
        T result = o; //上次的合并结果
        for (T t : collection) {
            result = operator.apply(result, t);
        }
        return result;
    }

    public static <T> SimpleStream2<T> of(Collection<T> collection) {
        return new SimpleStream2<>(collection);
    }

    private Collection<T> collection;

    private SimpleStream2(Collection<T> collection) {
        this.collection = collection;
    }
}